#include "global_config.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include <string.h> 
#include "esp_log.h"
#include "queue_demo.h"
#include "Arduino.h"
#define TAG "QueueDemo"

QueueDemo queueDemo; // 声明队列实例

// 构造函数
QueueDemo::QueueDemo() : value(0) {}

// 析构函数
QueueDemo::~QueueDemo() {}


TaskHandle_t Task1Handle, Task2Handle, Task3Handle;
QueueHandle_t countQueue;

int count = 0;

void Task1(void* parameter) {
  while (1) {
    digitalWrite(LED_BUILTIN_PIN, HIGH);
    vTaskDelay(1000 / portTICK_PERIOD_MS);
    digitalWrite(LED_BUILTIN_PIN, LOW);
    vTaskDelay(1000 / portTICK_PERIOD_MS);

    count++;
    Serial.print("Task1_count=");
    Serial.println(count);
    xQueueSend(countQueue, &count, portMAX_DELAY);
  }
}
void Task2(void* parameter) {
  while (1) {
      xQueueReceive(countQueue, &count, portMAX_DELAY);
      Serial.print("Receive count: ");
      Serial.println(count);
      if (count >= 10) {
        Serial.println("Task2_count>=10");
      } else {
        Serial.println("Task2_count<10");
      }
  }
}
void Task3(void *pvParameters) {
  while (1) {
      if (digitalRead(BTN_BOOT_PIN) == LOW) {
          count = 0;
          BaseType_t xStatus = xQueueSend(countQueue, &count, portMAX_DELAY);
          if (xStatus == pdPASS) {
              // 数据发送成功
              // 执行其他操作
              Serial.println("数据发送成功");
          } else {
              // 数据发送失败
              // 执行错误处理
              Serial.println("数据发送失败");
          }
      }
      vTaskDelay(10 / portTICK_PERIOD_MS);
  }
}

void QueueDemo::init()
{
    pinMode(BTN_BOOT_PIN, INPUT);
    pinMode(LED_BUILTIN_PIN, OUTPUT);
    Serial.println("Queue demo initialized");
    countQueue = xQueueCreate(100, sizeof(int));
    if(countQueue == NULL) {
        Serial.println("Failed to create Queue");
        return;
    }else{
        Serial.println("Queue created");
    }

    xTaskCreate(Task1, "Task1", 1024, NULL, 1, &Task1Handle);
    xTaskCreate(Task2, "Task2", 1024, NULL, 2, &Task2Handle);
    xTaskCreate(Task3, "Task3", 1024, NULL, 3, &Task3Handle);
}

void QueueDemo::deinit()
{
    Serial.println("Queue demo deinitialized");
}